/* eslint-disable */
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Form, Input, Button, Select, message, Menu, Layout, List, Space, Modal, Card } from 'antd';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import './TweetDetail.css';

const { Option } = Select;
const { Sider, Content } = Layout;

const TeacherPost = () => {
    const [form] = Form.useForm();
    const [currentView, setCurrentView] = useState('newPost');
    const [tweets, setTweets] = useState([]);
    const [drafts, setDrafts] = useState([]);
    const [trash, setTrash] = useState([]);
    const [deleteModalVisible, setDeleteModalVisible] = useState(false);
    const [permanentDeleteModalVisible, setPermanentDeleteModalVisible] = useState(false);
    const [deleteItemId, setDeleteItemId] = useState(null);
    const [viewTweetId, setViewTweetId] = useState(null);
    const [previewData, setPreviewData] = useState(null);

    const getToken = () => {
        return localStorage.getItem('token');
    };

    const fetchTweets = () => {
        axios.get('http://47.111.104.30:8080/api/v2/tweets', {
            headers: { 'Authorization': `Bearer ${getToken()}` }
        })
            .then(response => setTweets(response.data))
            .catch(error => console.error('Error fetching tweets:', error));
    };

    const fetchDrafts = () => {
        axios.get('http://47.111.104.30:8080/api/v2/tweets/drafts', {
            headers: { 'Authorization': `Bearer ${getToken()}` }
        })
            .then(response => setDrafts(response.data))
            .catch(error => console.error('Error fetching drafts:', error));
    };

    const fetchTrash = () => {
        axios.get('http://47.111.104.30:8080/api/v2/tweets/trash', {
            headers: { 'Authorization': `Bearer ${getToken()}` }
        })
            .then(response => setTrash(response.data))
            .catch(error => console.error('Error fetching trash:', error));
    };

    useEffect(() => {
        fetchTweets();
        fetchDrafts();
        fetchTrash();
    }, []);

    const onFinish = (values) => {
        // 创建一个临时 div 元素来解析 HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = values.description;
        // 获取纯文本内容
        values.description = tempDiv.textContent || tempDiv.innerText;

        axios.post('http://47.111.104.30:8080/api/v2/tweets', values, {
            headers: {
                'Authorization': `Bearer ${getToken()}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                message.success('推文创建成功');
                form.resetFields();
                fetchTweets();
            })
            .catch(error => {
                console.error('Error creating tweet:', error);
                message.error('Failed to create tweet.');
            });
    };

    const saveAsDraft = (values) => {
        values.status = 'draft';
        const isEditing = !!values.id;

        const url = isEditing
            ? `http://47.111.104.30:8080/api/v2/tweets/${values.id}`
            : 'http://47.111.104.30:8080/api/v2/tweets';

        const method = isEditing ? 'put' : 'post';

        axios[method](url, values, {
            headers: {
                'Authorization': `Bearer ${getToken()}`,
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                message.success('推文已保存为草稿');
                form.resetFields();
                fetchDrafts();
                if (isEditing) {
                    setCurrentView('drafts');
                }
            })
            .catch(error => {
                console.error('Error saving draft:', error);
                message.error('保存草稿失败');
            });
    };

    const deleteTweet = (id) => {
        setDeleteModalVisible(false);
        axios.delete(`http://47.111.104.30:8080/api/v2/tweets/${id}`, {
            headers: { 'Authorization': `Bearer ${getToken()}` }
        })
            .then(response => {
                message.success('推文已删除');
                fetchTweets();
                fetchDrafts();
                fetchTrash();
                setCurrentView('drafts'); // 删除后返回草稿箱
            })
            .catch(error => {
                console.error('Error deleting tweet:', error);
                message.error('Failed to delete tweet.');
            });
    };

    const permanentlyDeleteTweet = (id) => {
        setPermanentDeleteModalVisible(false);
        axios.delete(`http://47.111.104.30:8080/api/v2/tweets/permanent/${id}`, {
            headers: { 'Authorization': `Bearer ${getToken()}` }
        })
            .then(response => {
                message.success('推文已删除');
                fetchTrash();
            })
            .catch(error => {
                console.error('Error permanently deleting tweet:', error);
                message.error('Failed to permanently delete tweet.');
            });
    };

    const editDraft = (draft) => {
        form.setFieldsValue(draft);
        setCurrentView('newPost');
    };

    const previewTweet = () => {
        const formData = form.getFieldsValue();
        setPreviewData(formData);
        setCurrentView('preview');
    };

    const restoreTweet = async (id) => {
        try {
            await axios.put(`http://47.111.104.30:8080/api/v2/tweets/${id}/restore`, {}, {
                headers: { 'Authorization': `Bearer ${getToken()}` }
            });

            // 先更新垃圾箱数据
            await fetchTrash();
            // 再更新草稿箱数据
            await fetchDrafts();

            message.success('推文已恢复到草稿箱');
        } catch (error) {
            console.error('Error restoring tweet:', error);
            message.error('恢复推文失败');
        }
    };

    const renderContent = () => {
        switch (currentView) {
            case 'newPost':
                return (
                    <Card title="新建推文" bordered={false} style={{ width: '100%', maxWidth: '1100px', margin: 'auto', marginTop: '-20px', marginLeft: '10px' }}>
                        <Form form={form} onFinish={onFinish} layout="vertical">
                            <Form.Item name="id" hidden>
                                <Input />
                            </Form.Item>
                            <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题!' }]}>
                                <Input placeholder="输入标题" style={{ width: '100%', height: '50px' }} />
                            </Form.Item>
                            <Form.Item name="description" label="内容" rules={[{ required: true, message: '请输入内容!' }]}>
                                <ReactQuill theme="snow" placeholder="请输入推文内容" style={{ height: '300px', marginBottom: '40px' }} />
                            </Form.Item>
                            <Form.Item name="image" label="图片链接" rules={[{ required: true, message: '请输入图片链接!' }]}>
                                <Input placeholder="插入图片链接" style={{ width: '100%', height: '50px' }} />
                            </Form.Item>
                            <Form.Item>
                                <Space>
                                    <Button type="primary" htmlType="submit">发送</Button>
                                    <Button onClick={() => saveAsDraft(form.getFieldsValue())}>存为草稿</Button>
                                    {form.getFieldValue('id') && (
                                        <Button onClick={() => {
                                            setDeleteItemId(form.getFieldValue('id'));
                                            setDeleteModalVisible(true);
                                        }}>删除</Button>
                                    )}
                                    <Button onClick={previewTweet}>预览</Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Card>
                );
            case 'published':
                return (
                    <List
                        itemLayout="horizontal"
                        dataSource={tweets}
                        renderItem={tweet => (
                            <List.Item actions={[<a key="view" onClick={() => { setViewTweetId(tweet.id); setCurrentView('viewTweet'); }}>查看</a>]}>
                                <List.Item.Meta
                                    title={tweet.title}
                                    description={`发布时间: ${tweet.createdAt}`}
                                />
                            </List.Item>
                        )}
                    />
                );
            case 'drafts':
                return (
                    <List
                        itemLayout="horizontal"
                        dataSource={drafts}
                        renderItem={draft => (
                            <List.Item actions={[<a key="edit" onClick={() => editDraft(draft)}>编辑</a>, <a key="delete" onClick={() => { setDeleteItemId(draft.id); setDeleteModalVisible(true); }}>删除</a>]}>
                                <List.Item.Meta
                                    title={draft.title}
                                    description={`保存时间: ${draft.createdAt}`}
                                />
                            </List.Item>
                        )}
                    />
                );
            case 'trash':
                return (
                    <List
                        itemLayout="horizontal"
                        dataSource={trash}
                        renderItem={item => (
                            <List.Item
                                actions={[
                                    <a key="restore" onClick={() => restoreTweet(item.id)}>恢复</a>,
                                    <a key="delete" onClick={() => {
                                        setDeleteItemId(item.id);
                                        setPermanentDeleteModalVisible(true);
                                    }}>删除</a>
                                ]}
                            >
                                <List.Item.Meta
                                    title={item.title}
                                    description={`删除时间: ${item.createdAt}`}
                                />
                            </List.Item>
                        )}
                    />
                );
            case 'viewTweet':
                return (
                    <div>
                        <Button onClick={() => setCurrentView('published')} style={{ marginBottom: '20px' }}>返回</Button>
                        <TweetDetail tweetId={viewTweetId} />
                    </div>
                );
            case 'preview':
                return (
                    <div>
                        <Button onClick={() => setCurrentView('newPost')} style={{ marginBottom: '20px' }}>返回编辑</Button>
                        <div className="tweet-detail">
                            <img className="image" src={previewData.image} alt={previewData.title} />
                            <h1>{previewData.title}</h1>
                            <div className="description" dangerouslySetInnerHTML={{ __html: previewData.description }} />
                        </div>
                    </div>
                );
            default:
                return null;
        }
    };

    return (
        <Layout style={{ minHeight: '80vh' }}>
            <Sider width={200} className="site-layout-background" style={{ marginLeft: '10px' }}>
                <Menu
                    mode="inline"
                    defaultSelectedKeys={['newPost']}
                    selectedKeys={[currentView]}
                    style={{ height: '100%', borderRight: 0, textAlign: 'center' }}
                    onClick={(e) => setCurrentView(e.key)}
                >
                    <Menu.Item key="newPost">新建推文</Menu.Item>
                    <Menu.Item key="published">已发布</Menu.Item>
                    <Menu.Item key="drafts">草稿箱</Menu.Item>
                    <Menu.Item key="trash">回收站</Menu.Item>
                </Menu>
            </Sider>
            <Layout style={{ padding: '0 24px 24px' }}>
                <Content
                    style={{
                        padding: 24,
                        margin: 0,
                        backgroundColor: '#fff', 
                    }}
                >
                    {renderContent()}
                </Content>
            </Layout>

            <Modal
                title="确认删除"
                visible={deleteModalVisible}
                onOk={() => deleteTweet(deleteItemId)}
                onCancel={() => setDeleteModalVisible(false)}
            >
                <p>确认删除该推文吗？</p>
            </Modal>

            <Modal
                title="确认永久删除"
                visible={permanentDeleteModalVisible}
                onOk={() => permanentlyDeleteTweet(deleteItemId)}
                onCancel={() => setPermanentDeleteModalVisible(false)}
            >
                <p>确认删除该推文，此操作将永久删除此推文。</p>
            </Modal>
        </Layout>
    );
};

// eslint-disable-next-line react/prop-types
const TweetDetail = ({ tweetId }) => {
    const [tweet, setTweet] = useState(null);

    useEffect(() => {
        const fetchTweet = async () => {
            try {
                const response = await axios.get(`http://47.111.104.30:8080/api/v2/tweets/${tweetId}`, {
                    headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
                });
                if (response.status === 200) {
                    setTweet(response.data);
                }
            } catch (error) {
                console.error("获取推文失败:", error.message);
            }
        };

        fetchTweet();
    }, [tweetId]);

    if (!tweet) {
        return <p>loading...</p>;
    }

    return (
        <div className="tweet-detail">
            <img className="image" src={tweet.image} alt={tweet.title} />
            <h1>{tweet.title}</h1>
            <div className="description" dangerouslySetInnerHTML={{ __html: tweet.description }} />
        </div>
    );
};

export default TeacherPost;